/*
 * (C) APUE
 * fork twice to prevent zombie process
 */
#include "apue.h"
#include <sys/wait.h>

int main()
{
	pid_t pid;

	if ((pid = fork()) < 0)
		err_quit("fork error");
	else if (pid == 0) /* first child */
	{
		if ((pid = fork()) < 0)
			err_quit("fork error");
		else if (pid > 0)	/* still first child = second child's parent */
			exit(0);

		/* 
		 * now we are in the second child .
		 * sleep is waiting for the termination of the first child
		 * and we will see that the 2nd child's parent changes to init(whose ID is 1).
		 */
		sleep(2);
		printf("second child, parent pid is %d\n", getppid());
		exit(0);
	}

	/* here we handle the first child */
	if (waitpid(pid, NULL, 0) != pid)
		err_quit("waitpid error");

	exit(0);
}
